import express from 'express';
import  lodash from 'lodash';

import  tableModule from '../models/index.js';
const {usersModel} = tableModule

const router = express.Router()


// 注册账户
router.post('/register',async (req,res)=>{
    const { userName,password,phone, randomQuestion} = req.body;
    // 用户名校验
   let userByUserName = await usersModel.getUserByUniqueIdentifier({userName})
    if(userName && userByUserName){
        res.json({
            code:500,
            message:"用户名已存在，请重新输入",
            data:false
        })
        return
    }

    // 密码校验
    if(password && password?.length < 6){
        res.json({
            code:500,
            message:"密码长度不能小于6位",
            data:false
        })
        return
    }


    // 手机号校验 
    let phoneRegex = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/
    if(phone && !phoneRegex?.test(phone)){
        res.json({
            code:500,
            message:"手机号格式不正确",
            data:false
        })
        return
    }

    //手机号重复校验
    let userByPhone = await usersModel.getUserByUniqueIdentifier({phone})
    if(phone && userByPhone){
         res.json({
            code:500,
            message:"当前手机号已绑定其他账户，请重新输入",
            data:false
        })
        return
    }



    //信息完整校验
    if(userName && password && phone && randomQuestion?.length > 0){
        let fullSuccess = true
        let newRandomQuestion =  randomQuestion?.map((item,index)=>{
            if(!item.question || !item.answer){
                fullSuccess = false
            }
            return {
                id:(index+1).toString(),
                question:item.question,
                answer:item.answer
            }
        }) 

        if(fullSuccess){
            let addRes = await usersModel.addUser({userName,password,phone,randomQuestion:newRandomQuestion})
            if(addRes){
                return res.json({
                    code:200,
                    message:"注册成功",
                    data:true
                })
            }else{
                return res.status(500).json({
                    code:500,
                    mesage:"注册失败",
                    data:false
                })
            }
        }else{
            return res.status(500).json({
                code:500,
                mesage:"随机问题内容不完整，注册失败",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            mesage:"参数不完整，注册失败",
            data:null
        })
    }
})


// 查询用户信息关联的随机问题  
router.post('/searchUserRandomQuestion',async(req,res)=>{
    const {userId,userName,phone} = req.body;
    let result = await usersModel.getUserByUniqueIdentifier({userId,userName,phone})
    if(result){
        let tmpRandomQuestion = typeof result.randomQuestion === 'string' ? JSON.parse(result.randomQuestion) : result.randomQuestion
        let randomQuestionTitleList = tmpRandomQuestion.map(item=>{
            return {
                id:item.id,
                question:item.question
            }
        })
        res.json({
            code:200,
            message:"查询成功",
            
            data:randomQuestionTitleList || []
        })
    }else{
        res.status(500).json({
            code:500,
            message:"用户信息不存在",
            data:null
        })
    }
})


// 找回密码
router.post('/findPassword', async (req,res)=>{
    const {userName,phone,randomQuestion} = req.body;
    let result = null

    //通过手机号和用户名找回
    if(userName && phone){
        result = await usersModel.getUserByUniqueIdentifier({userName,phone})
        if(result){
            return res.json({
                code:200,
                message:'找回成功',
                data:{password:result?.password || null}
            })
        }else{
            return res.json({
                code:500,
                message:'用户信不匹配，请重新输入',
                data:null
            })
        }
    }
    
    // 通过手机号和随机问题找回 或者 用户名和随机问题找回
    if( phone && randomQuestion?.length > 0){
        result = await usersModel.getUserByUniqueIdentifier({phone})
        
        //判断随机问题是否在查询结果当中
        let match = false
        randomQuestion.forEach((item1)=>{
            result?.randomQuestion.find((item2)=>{
                if(lodash.isEqual(item1,item2)){
                    match = true
                }
            })
        })
        if(!match || !result){
            return res.json({
                code:500,
                message:"用户信不匹配，请重新输入",
                data:null
            })
        }else{
            return res.json({
                code:200,
                message:'找回成功',
                data:{password:result?.password || null}
            })
        }
    }

    // 参数不完整的校验
    return res.status(500).json({
        code:200,
        mesage:"参数不完整，请求失败",
        data:null
    })

})

export default router;